/*
* Copyright 2017 Yonyou Auto Information Technology（Shanghai） Co., Ltd. All Rights Reserved.
*
* This software is published under the terms of the YONYOU Software
* License version 1.0, a copy of which has been included with this
* distribution in the LICENSE.txt file.
*
* @Project Name : marketing-service-information
*
* @File name : InformationServie.java
*
* @Author : Administrator
*
* @Date : 2017年3月10日
*
----------------------------------------------------------------------------------
*     Date       Who       Version     Comments
* 1. 2017年3月10日    Administrator    1.0
*
*
*
*
----------------------------------------------------------------------------------
*/
	
package com.yonyou.gmmc.service.information.service;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.log4j.Logger;
import org.marketing.common.FrameHttpUtil;
import org.marketing.common.constants.BusinessConstant;
import org.marketing.common.constants.CommonConstant;
import org.marketing.common.dms.dto.IfMessage;
import org.marketing.common.dto.SendTicket;
import org.marketing.common.dto.information.ActivityInfoDto;
import org.marketing.common.dto.information.ActivityItemsDto;
import org.marketing.common.dto.information.ActivityRecordDto;
import org.marketing.common.dto.information.ReadingDto;
import org.marketing.common.dto.leads.ThreadcarDto;
import org.marketing.common.event.BizEvent;
import org.marketing.common.event.EventActivityInfoReadDTO;
import org.marketing.common.event.EventCapitalSendMessageDTO;
import org.marketing.common.event.enums.EventConstant.EventBizStep;
import org.marketing.common.event.enums.EventConstant.EventBizType;
import org.marketing.common.exception.ServiceBizException;
import org.marketing.common.util.CheckUtil;
import org.marketing.common.util.CommonUtils;
import org.marketing.common.util.MD5Util;
import org.marketing.common.util.MapConverUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestBody;
import com.alibaba.fastjson.JSON;
import com.yonyou.gmmc.common.service.BaseService;
import com.yonyou.gmmc.common.service.BaseService.MQChannelType;
import com.yonyou.gmmc.common.sms.SmsHttpClient;
import com.yonyou.gmmc.service.information.constant.InformationConstant;
import com.yonyou.gmmc.service.information.constant.RequestLimit;
import com.yonyou.gmmc.service.information.dao.TtActivityApplyRecordMapper;
import com.yonyou.gmmc.service.information.dao.TtMaintenanceRecordMapper;
import com.yonyou.gmmc.service.information.dao.TtReadingStatisticsMapper;
import com.yonyou.gmmc.service.information.entity.NewsActivityPO;
import com.yonyou.gmmc.service.information.model.TtActivityApplyRecord;
import com.yonyou.gmmc.service.information.model.TtBlackList;
import com.yonyou.gmmc.service.information.model.TtReadingStatistics;

/**
*
* @author Administrator
* @date 2017年3月10日
*/
@Transactional
@Service("informationService")
public class InformationService {

    private Logger       logger = Logger.getLogger(InformationService.class);
    
    @Autowired
    private TtMaintenanceRecordMapper ttMaintenanceRecordMapper;
    
    @Autowired
    private TtActivityApplyRecordMapper ttActivityApplyRecordMapper;
    @Autowired
    private TtReadingStatisticsMapper ttReadingStatisticsMapper;
    
    @Autowired
    private BaseService eventService; 
    
    @Value("${inforhost}")
    private String inforHost;
    
    @Value("${SMS-pass}")
    private String                   smsPass;
    
    @Value("${SMS-key}")
    private String                   smsKey;
    
    @Value("${SMS_CDKEY}")
    private String                   SMS_CDKEY;
    
    @Value("${SMS_PASS}")
    private String                   SMS_PASS;
    
    @Value("${SMS_BASEURL}")
    private String                   SMS_BASEURL;
    
    public String getInforNews(Integer naiId,Integer type) {
    	NewsActivityPO dtoList = ttMaintenanceRecordMapper.queryNewsActivityById(naiId,type);
        String remark = "";
        if(dtoList.getCapital()==null){
            remark = "-1";
        }else{
            remark = dtoList.getCapital().toString();
        }
        return remark;
    }
    
    /**
    * 根据路径获取新闻资讯内容
    * @author QianKun
    * @date 2017年3月10日
    * @param naiId
    * @return
    */
    public String getNewsActivityContent(Integer naiId,Integer type) {
        NewsActivityPO newsActivityPO = ttMaintenanceRecordMapper.queryNewsActivityById(naiId,type);
        String contentPath = newsActivityPO.getContentPath();
        if(CheckUtil.NullOrEmpty(contentPath)){
            return BusinessConstant.EMPTY_STRING;
        }
        return CommonUtils.getUrlToContent(contentPath);
    }

    
    /**
    * 保存留资信息
    * @author QianKun
    * @date 2017年3月10日
    * @param capitalInformationDto
    * @return
    */
    @RequestLimit(count=30,time=1000)
    public Map<String, Object> saveCapitalInfor(@RequestBody ThreadcarDto threadcarDto) {
        Map<String, Object> map = new HashMap<>();
        try {
           logger.info("校验：一个手机号只能报名同一个活动一次"); 
           String threadId = ttMaintenanceRecordMapper.selectCapitalInfor(threadcarDto);
           if(!CheckUtil.NullOrEmpty(threadId)){
               logger.info("该手机已在此资讯留资过！");
               map.put("errorCode", "1");
               map.put("errorMsg","该手机已留资过该资讯，不允许重复留资！");
           }else{
               logger.info("该手机尚未在此资讯留资！");
               int a = ttMaintenanceRecordMapper.saveCapitalInfor(threadcarDto);
               logger.info("新增"+a+"条留资");
               map.put("errorCode", "0");
               map.put("errorMsg", "留资成功！");
               //潜客留资信息
               CapitalInfor(threadcarDto);
           }
        } catch (Exception e) {
            logger.info("Exception:", e);
            map.put("errorCode", "1");
            map.put("errorMsg", "留资失败！");
        }
        return map;
    }
    
    /**
    * 活动填写项目查询
    * @author QianKun
    * @date 2017年3月10日
    * @param naiId
    * @return
    */
    public List<ActivityItemsDto> getActivityItems(Long naiId) {
    	List<ActivityItemsDto> dtoList = ttMaintenanceRecordMapper.queryActivityItems(naiId);
        return dtoList;
    }
    
    /**
    * 新增报名人信息
    * @author QianKun
    * @date 2017年3月11日
    * @param activityRecordDto
    * @return
    */
    @RequestLimit(count=30,time=1000)
    public Map<String, Object> insertPotentialUser(@RequestBody ActivityRecordDto activityRecordDto) {
        Map<String, Object> map = new HashMap<>();
        logger.info("校验：一个手机号只能报名同一个活动一次");
        List<TtActivityApplyRecord> list = ttActivityApplyRecordMapper.selectActivityRecord(activityRecordDto);
        if(CheckUtil.NullOrEmpty(list)){
            logger.info("该手机号暂未报名此次活动");
            int a = ttMaintenanceRecordMapper.insertPotentialUser(activityRecordDto);
            logger.info("新增了"+a+"条活动报名记录");
            map.put("errorCode", "0");
            map.put("errorMsg", "报名成功！");
        }else{
            logger.info("该手机号已报名过该活动");
            map.put("errorCode", "1");
            map.put("errorMsg","该手机已报名过该活动，不允许重复报名！");
        }
        return map;
    }
    
    /**
    * 统计阅读量
    * @author QianKun
    * @date 2017年3月13日
    * @param readingDto
    * @return
    */
    public Map<String, Object> saveReadingNum(ReadingDto readingDto){
        Map<String, Object> map = new HashMap<>();
        //查询是否已存在该条记录
        TtReadingStatistics readSt = new TtReadingStatistics();
        readSt.setUserId(readingDto.getUserId());
        readSt.setObjectId(readingDto.getObjectId());
        List<TtReadingStatistics> dtoList = ttReadingStatisticsMapper.select(readSt);
        if(CheckUtil.NullOrEmpty(dtoList)){
        	TtReadingStatistics read = new TtReadingStatistics();
        	read.setUserId(readingDto.getUserId());
        	read.setReadingNum(0L);
        	read.setObjectType(readingDto.getObjectType());
        	read.setObjectId(readingDto.getObjectId());
        	read.setCreateDate(new Date());
        	map.put("resultDate", "1");
        	ttReadingStatisticsMapper.insertSelective(read);
        }else{
            //有记录,先自+1
            ttMaintenanceRecordMapper.updateReadingNum(readingDto);
            //自+1之后查询当前阅读量
            TtReadingStatistics read1 = new TtReadingStatistics();
            read1.setUserId(readingDto.getUserId());
            read1.setObjectId(readingDto.getObjectId());
            List<TtReadingStatistics> readingList = ttReadingStatisticsMapper.select(read1);
            for(TtReadingStatistics readDto:readingList){
                if(readDto.getReadingNum()%InformationConstant.EFFECTIVE_READING_NUMBER==0){
                    //判段是否为会员，车主
                	List<Map<String,Object>> memDto = ttMaintenanceRecordMapper.selectUserAndCar(Integer.valueOf(readingDto.getUserId()));
                	String phone = "";
                    if(CheckUtil.NullOrEmpty(memDto)){
                        //不是车主，不做处理
                    }else{
                    	phone = memDto.get(0).get("PHONE")==null?"":memDto.get(0).get("PHONE").toString();
                        //是车主，获取积分
                        readingDto.setPhone(phone);
                        //符合获取积分规则
                        map.put("resultDate", "2");
                        EventActivityInfoReadDTO acDto = new EventActivityInfoReadDTO();
                        acDto.setUserId(Integer.valueOf(readingDto.getUserId()));
                        acDto.setInfoId(readDto.getObjectId());
                        acDto.setReadNum(readDto.getReadingNum().intValue());
                        acDto.setPhone(phone);
                        BizEvent event = new BizEvent();
                        event.setEventBizType(EventBizType.ACTIVITY_INFO);
                        event.setEventBizStep(EventBizStep.ACTIVITY_INFO_READ);
                        event.setEventKey("YDTJ"+"-"+readingDto.getObjectId()+"-"+readingDto.getUserId()+"-"+readDto.getReadingNum());
                        event.setEventData(MapConverUtil.PO2Map(acDto));
                        String s = "";
						try {
							s = eventService.sendEvent2MQ(event);
						} catch (Exception e) {
							throw new ServiceBizException(e.getMessage(), e);
						}
                        logger.info("MQ返回结果>>>>>>>>>>>>>>>>>>>>"+s);
                        //根据UserId查询OpenId
                        String userId = readingDto.getUserId();
                        logger.info("该用户的车主ID为>>>>>>"+userId);
                        String openId = ttMaintenanceRecordMapper.selectOpenId(userId);
                        logger.info("查询到的OpenId为》》》》》"+openId);
                        //查询积分变动数
//                        String points = ttMaintenanceRecordMapper.selectPointsChange();
//                        logger.info("查询到的积分变动数为》》》》》"+points);
                        //调用接口
//                        String x = pointactivityServiceInteface.sendMaxTurntable(openId, points);
//                        String x = sendMaxTurntable(openId, points);
//                        logger.info("接口返回结果:"+x);
                    }
                   }else{
                    //不符合获取积分
                    map.put("resultDate", "3");
                }
            }
        }
        return map;
    }
    
    public Map<String, Object> sendTicket(@RequestBody ReadingDto readingDto) {
        Map<String, Object> map = new HashMap<String, Object>();
        try{
            //发放卡券
            Integer userId = Integer.valueOf(readingDto.getUserId());
            logger.info("潜客ID为："+userId);
            logger.info("自动发放卡券");
            SendTicket ticketDto = new SendTicket();
            ticketDto.setBizCode(1007);
            ticketDto.setTriggerCode(10071001);
            ticketDto.setUserId(userId);
            List<Map<String,Object>> list = ttMaintenanceRecordMapper.selectUserAndCar(userId);
        	String dealerCode = "";
        	if(!CheckUtil.NullOrEmpty(list)){
        		dealerCode = list.get(0).get("DEALER_CODE")==null?"":list.get(0).get("DEALER_CODE").toString();
        	}
            logger.info("该用户的销售店为："+dealerCode);
            if(dealerCode!=null){
                ticketDto.setDealerCode(dealerCode);
            }else{
                ticketDto.setDealerCode("");
            }
            ticketDto.setBatchId("");
            ticketDto.setBizId(readingDto.getObjectId().toString());
            BizEvent et = new BizEvent();
            et.setEventBizType(EventBizType.SEND_TICKET);
            et.setEventBizStep(EventBizStep.SEND_TICKTE_TO_USER);
            et.setEventKey("TICKET:"+ticketDto.getUserId()+":"+new Date().getTime());
            et.setEventData(MapConverUtil.PO2Map(ticketDto));
            String s = eventService.sendEvent2MQ(et);
            logger.info("发放卡券MQ返回结果>>>>>>>>>>>>>>>>>>>>" + s);
            map.put("resultCode", "200");
            map.put("resultMsg", "自动发放卡券成功");
            return map;
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            throw new ServiceBizException(e.getMessage(), e);
        }
    }
    
    public String sendMaxTurntable(String openId,String integral) {

        Map<String, String> param = new HashMap<String, String>();
        param.put("openid", openId);
        param.put("integral", integral);
        param.put("archiveId", "SlyderAdventures");

        return  FrameHttpUtil.post(InformationConstant.slyderAdventuresURL, param);
    }
    
    public static boolean isNull(String str){
        return (str== null || "".equals(str.trim()));
    }
    
    /**
    * 已报名信息列表查询
    * @author QianKun 
    * @date 2017年3月15日
    * @param openId
    * @return
    */
    public List<ActivityRecordDto> getActivityList(String userId) {
    	List<ActivityRecordDto> dtoList = ttMaintenanceRecordMapper.queryActivityList(userId);
        return dtoList;
    }
    
    /**
    * 已报名信息详情查询
    * @author QianKun
    * @date 2017年3月15日
    * @param applyId
    * @return
    */
    public List<ActivityRecordDto> getActivityInfo(Long applyId) {
    	List<ActivityRecordDto> dtoList = ttMaintenanceRecordMapper.queryActivityMemberInfo(applyId);
        return dtoList;
    }
    
    /**
    * 我能看到的资讯查询 
    * @author QianKun
    * @date 2017年3月16日
    * @param openId
    * @return
    */
    public List<ActivityInfoDto> getMyNews(String userId,Long activityType) {
    	List<Map<String,Object>> list = ttMaintenanceRecordMapper.selectUserAndCar(Integer.valueOf(userId));
    	String userType = "";
    	String dealerCode = "";
    	if(CheckUtil.NullOrEmpty(list)){
    		userType = "%1%";
    	}else if(CheckUtil.NullOrEmpty(list.get(0).get("CAR_ID"))){
    		userType = "%2%";
    		dealerCode = list.get(0).get("DEALER_CODE")==null?"":list.get(0).get("DEALER_CODE").toString();
    	}else{
    		userType = "%3%";
    		dealerCode = list.get(0).get("DEALER_CODE")==null?"":list.get(0).get("DEALER_CODE").toString();
    	}
    	List<ActivityInfoDto> dtoList = ttMaintenanceRecordMapper.queryMyNews(userType,dealerCode,activityType);
        return dtoList;
    }
    
    /**
    * 我能看到的活动查询
    * @author QianKun
    * @date 2017年3月16日
    * @param openId
    * @return
    */
    public List<ActivityInfoDto> getMyActivities(String userId) {
    	List<Map<String,Object>> list = ttMaintenanceRecordMapper.selectUserAndCar(Integer.valueOf(userId));
    	String userType = "";
    	String dealerCode = "";
    	if(CheckUtil.NullOrEmpty(list)){
    		userType = "%1%";
    	}else if(CheckUtil.NullOrEmpty(list.get(0).get("CAR_ID"))){
    		userType = "%2%";
    		dealerCode = list.get(0).get("DEALER_CODE")==null?"":list.get(0).get("DEALER_CODE").toString();
    	}else{
    		userType = "%3%";
    		dealerCode = list.get(0).get("DEALER_CODE")==null?"":list.get(0).get("DEALER_CODE").toString();
    	}
    	List<ActivityInfoDto> dtoList = ttMaintenanceRecordMapper.queryMyActivity(userType,dealerCode);
        
        return dtoList;
    }

    
    /**
    * 潜客留资信息
    * @author Administrator
    * @date 2017年3月25日
    * @param threadcarDto
    * @throws Exception
    */
    public void CapitalInfor(@RequestBody ThreadcarDto threadcarDto) throws Exception{
        IfMessage<List<EventCapitalSendMessageDTO>> l=new IfMessage<>();
        List<EventCapitalSendMessageDTO> list=new ArrayList<>();
        EventCapitalSendMessageDTO cpSend = new EventCapitalSendMessageDTO();
        cpSend.setName(threadcarDto.getFriendname());
        cpSend.setMobile(threadcarDto.getFriendphone());
        list.add(cpSend);
        l.setIfData(list);
        String time = String.valueOf(new Date().getTime());
        String transferNo = MD5Util.MD5("IC005" + time + CommonConstant.HTTP_CLUB_KEY);

        l.setIfCode("IC005");
        l.setOccurtime(time);
        l.setTransferNo(transferNo);
        l.setDataCnt(1);
        logger.info("SendToMQ");
        String s = eventService.sendMessage2MQ(MQChannelType.appAppointmentInfo,JSON.toJSONString(l).toString());
        //eventService.sendEvent2MQ(event);
        logger.info("MQ返回结果>>>>>>>>>>>>>>>>>>>>"+s);
        logger.info("SendEnd");
    }
    
    public int addBlackList(TtBlackList blackList){
        int i = ttMaintenanceRecordMapper.addBlackList(blackList);
        return i;
    }
    
    public List<TtBlackList> findByIp(String ip){
        List<TtBlackList> list = new ArrayList<TtBlackList>();
        list = ttMaintenanceRecordMapper.findByIp(ip);
        return list;
    }

    /**
     * 查询订单号
     * @return
     */
	public String checkShoppingPoints() {
		String result="OK，没有问题";
        List<Map<String,Object>> mapList = ttActivityApplyRecordMapper.queryOrderList();
        /*Map<String,Object> mmp = new HashMap<String,Object>();
        mmp.put("thirdOrder", "JD0000000000");
        mmp.put("jdOrderId", "000000");
        mapList.add(mmp);*/
        logger.info("查询结果："+mapList);
        if(!mapList.isEmpty()){
        	logger.info("有存在问题订单，请及时查看！");
        	String userName="ADMIN_PHONE";
        	String userName2="ADMIN_PHONE_TWO";
        	String phone = ttActivityApplyRecordMapper.queryAdminPhone(userName);
        	String phone2 = ttActivityApplyRecordMapper.queryAdminPhone(userName2);
        	logger.info("发送手机号："+phone+"，手机号2："+phone2);
        	String message ="有存在问题订单，请及时查看！ ";
        	Map<String,Object> map = mapList.get(0);
    		message += "订单编号："+map.get("thirdOrder").toString();
    		logger.info("短信内容："+message);
    		String s = SmsHttpClient.sendSms(phone, message, smsPass, smsKey,
                    SMS_CDKEY, SMS_PASS, SMS_BASEURL);
    		logger.info("短信平台返回结果："+s);
    		String s2 = SmsHttpClient.sendSms(phone2, message, smsPass, smsKey,
                    SMS_CDKEY, SMS_PASS, SMS_BASEURL);
    		logger.info("短信平台返回结果2："+s2);
        	result = message;
        }else{
        	logger.info("没有发现有问题的订单。");
        }
        return result;
	}
}
